import Taro, { getCurrentInstance } from '@tarojs/taro';
import React from 'react'
import { connect } from 'react-redux'
import map from '@/utils/map'
import { CrossDomain } from '@/utils/cross-domain'
import { nearStore, storeInfo } from '@/api'
import { updateShareLog } from '@/api/distribution'
import { updateStore, initLocation, setOpenLocation } from '@/store/location/action'
// 引入 WebView 组件
import { WebView, View, CoverView } from '@tarojs/components'
import { carInfo } from '@/store/car/action'
import { loginMethod } from '@/utils/login'
import onNavigation from '@/utils/command/onNavigation'
const domain: string = `${BASE_H5_URL}/#`
type State = {
  webUrl: string,
  currentCar: any
  shareImgUrl: any,
  shareMobile: any,
  shareTitle: any,
  shareId: any,
  sharePath: any,
  superiorMobile: any,

  distributionUserId: any,
  selectArea: any,
  jihuasuanId: any,
  cheapShshareTitle: any,
  cheapShareImgUrl: any,
  pMobile: any,
  ppMobile: any,
  cheapSharePath: any,
  linkType: any,
  jihuasuanGoodsId: any,
  referId: any,
  mobile: any
  commShareTitle: any
  commSharePath: any

}
type paramsData = {
  duid: any,
  carId: string,
  accessId: string,
  accessKey: string,
  storeCode: String,
  serverTime: number,
  distributionLeaderId: any,
  userId: string,
  mobile: [number, string],
  thirdPartySource: string,
  cityCode?: any
  areaCode?: any
  code?: String
  selectArea?: any
}
let whiteList = ['jekunauto.qiyukf.com']
@connect<any>(({ location, car, maintain, user }) => ({ location, car, maintain, user }), _dispatch => ({
  dispatchStore(params) {
    return _dispatch(updateStore(params))
  },
  // 缓存 当前区域经纬度，当前区域信息，城市名
  dispatchLocation(params) {
    return _dispatch(initLocation(params))
  },
  // 位置授权状态（true: 已开启，false: 未开启）
  dispatchOpenLocation(status) {
    return _dispatch(setOpenLocation(status))
  },
  dispatchCarInfo() {
    return _dispatch(carInfo())
  }
}))

export default class AppWebView extends React.Component<any, State> {
  $instance = getCurrentInstance()
  async handleMessage(e) {
    console.log(e)
  }

  config = {
    navigationBarTitleText: '',
    enablePullDownRefresh: true
  }
  protected __data__: any
  constructor (props) {
    super(props)
    this.state = {
      webUrl: '',
      currentCar: {},
      shareImgUrl: '',
      shareMobile: '',
      shareTitle: '',
      shareId: '',
      sharePath: '',
      superiorMobile: '',
      distributionUserId: '',
      selectArea: {},
      jihuasuanId: '',
      cheapShshareTitle: '',
      cheapShareImgUrl: '',
      pMobile: '',
      ppMobile: '',
      cheapSharePath: '',
      linkType: '',
      referId: '',
      jihuasuanGoodsId: '',
      mobile: '',
      commSharePath: '',
      commShareTitle: '',
    },
      this.__data__ = process.env.TARO_ENV === 'weapp' ? '__data__' : 'data'
  }
  async componentDidShow() {
    let pages = Taro.getCurrentPages();
    let currentPage = pages[pages.length - 1]; // 获取当前页面
    if (currentPage[this.__data__].selectArea) { // 获取值
      this.setState({
        selectArea: currentPage[this.__data__].selectArea
      })
      console.log('进来的selectArea数据', currentPage[this.__data__].selectArea)
    }

  }
  async UNSAFE_componentWillMount() {
    console.log('--进来webview--')
    console.log('this.$instance.router', this.$instance.router)
    let { userId } = this.props.user.userInfo
    if (!userId) { // 有登录状态才获取
      loginMethod()
      return
    }
    let { query, path, rest } = this.$instance.router.params
    let selectArea = this.state.selectArea
    let te: any = Taro.getStorageSync('DISTRIBUTION_LEADER_TYPE')
    let sId: any = Taro.getStorageSync('DISTRIBUTION_SHARE_ID')
    let um: any = Taro.getStorageSync('DISTRIBUTION_USER_MOBILE')
    let duid: any = Taro.getStorageSync('DUID') || query && query.duid || ''
    let superiorMobile = Taro.getStorageSync('DISTRIBUTION_SUPERIOR_MOBILE')
    let pId = Taro.getStorageSync('CHEAP_PID')
    let act = Taro.getStorageSync('CHEAP_ACT')
    let rId = Taro.getStorageSync('CHECK_REPORT_ID')
    const resulte = await Taro.login()
    if (te && te == '2') {
      path = '/insurance/upKeep/transact/puls'
      query = JSON.stringify({ type: 'oil_puls' })
    }
    if (te && te == '3') {
      path = '/insurance/upKeep/transact/puls'
      query = JSON.stringify({ type: 'tyre_puls' })
    }
    if (sId) {
      path = '/invite/share'
      query = JSON.stringify({ shareId: sId, shareMobile: um, superiorMobile: superiorMobile })
      console.log('query---query', query)
    }
    if (duid) {
      path = '/retail/activity'
      query = JSON.stringify({ duid: duid })
      console.log('query--duid--query', query)
    }
    if (pId) {
      path = '/cheap/user'
      query = JSON.stringify({ jihuasuanId: act, pId: pId })
      console.log('query---query', query)
    }
    if (rId) { // 检测报告Id
      path = '/check/report'
      query = JSON.stringify({ reportId: rId })
      console.log('query---query', query)
      console.log('执行进来了吗----')
    }
    let authInfo: any = Taro.getStorageSync('IS_USERINFO')
    let distributionLeaderId: any = Taro.getStorageSync('DISTRIBUTION_LEADER_ID')
    let herf = this.setHref(path, query)

    // 判断是否有门店信息  有直接跳转  没有获取附近门店列表取最近
    const storeCode = Taro.getStorageSync('STORECODE')
    if (!storeCode) {
      const { dispatchOpenLocation, location, dispatchLocation } = this.props
      //获取位置信息
      let curLocation: any = await map.getLocation(true)
      const { isOpenLocation } = location
      if (curLocation) {
        if (!isOpenLocation) {
          // 当用户开启定位授权，更新状态
          if (curLocation) {
            await dispatchOpenLocation(true)
          } else {
            // 没有开启定位授权，如果有历史地址，则拿历史记录地址
            const storageAddress = Taro.getStorageSync('CUSTOMA_DDRESS')
            if (storageAddress) {
              dispatchLocation(storageAddress)
              return
            }
          }
        }
        await this.getNearStore(curLocation)
      }
    }
    /**
     * 白名单内的域名不携带登录信息
     */
    let needLoginData = true
    whiteList.forEach(e => {
      console.log(e, path, path.indexOf(e) == -1)
      if (path.indexOf(e) >= 0) {
        needLoginData = false
      }
    })
    console.log('needLoginData', needLoginData)
    if (!this.props.car.carInfo.currentCar && authInfo) {
      Taro.showLoading({ title: '拉取车型数据中' })
      this.props.dispatchCarInfo().then(() => {
        let data: paramsData = {
          duid: duid ? duid : '',
          carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
          accessId: authInfo.accessId,
          userId: authInfo.userId,
          accessKey: authInfo.accessKey,
          storeCode: Taro.getStorageSync('STORECODE'),
          serverTime: authInfo.serverTime,
          distributionLeaderId: distributionLeaderId ? distributionLeaderId : '',
          mobile: authInfo.mobile,
          thirdPartySource: Taro.getStorageSync('THIRD_PARTY_SOURCE') ? Taro.getStorageSync('THIRD_PARTY_SOURCE') : 'JEKUNAUTO',
          cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
          areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : '',
          // thirdPartySource: 'JHYC',
          code: resulte.code,
          selectArea
        }
        let parameter = { url: herf }
        if (needLoginData) {
          parameter.data = data
        }
        let url = new CrossDomain(parameter).init()
        if (rest) {
          url = `${url}&${rest}`
        }
        console.log('执行进来这儿了吗！！！！！', url)
        this.setState({
          webUrl: url
        }, () => {
          console.log('執行---------------------22222222222222222')
          Taro.setStorageSync('DISTRIBUTION_SHARE_ID', '')
          Taro.setStorageSync('DISTRIBUTION_USER_MOBILE', '')
          Taro.setStorageSync('DISTRIBUTION_SUPERIOR_MOBILE', '')
          Taro.setStorageSync('DUID', '')
          Taro.setStorageSync('CHEAP_PID', '')
          Taro.setStorageSync('CHEAP_ACT', '')
          Taro.setStorageSync('CHECK_REPORT_ID', '')
        })
        Taro.hideLoading()
      })
    } else {
      let data: paramsData = {
        duid: duid ? duid : '',
        carId: this.props.car.carInfo.currentCar ? this.props.car.carInfo.currentCar.id : '',
        accessId: authInfo.accessId,
        accessKey: authInfo.accessKey,
        userId: authInfo.userId,
        storeCode: Taro.getStorageSync('STORECODE'),
        serverTime: authInfo.serverTime,
        distributionLeaderId: distributionLeaderId ? distributionLeaderId : '',
        mobile: authInfo.mobile,
        thirdPartySource: Taro.getStorageSync('THIRD_PARTY_SOURCE') ? Taro.getStorageSync('THIRD_PARTY_SOURCE') : 'JEKUNAUTO',
        cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
        areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : '',
        code: resulte.code,
        selectArea
        // thirdPartySource: 'JHYC'
      }
      let parameter = { url: herf }
      if (needLoginData) {
        parameter.data = data
      }
      let url = new CrossDomain(parameter).init()
      if (rest) {
        url = `${url}&${rest}`
      }
      this.setState({
        webUrl: url,
        currentCar: this.props.car.carInfo.currentCar
      }, () => {
        console.log('執行---------------------111111111')
        Taro.setStorageSync('DISTRIBUTION_SHARE_ID', '')
        Taro.setStorageSync('DISTRIBUTION_USER_MOBILE', '')
        Taro.setStorageSync('DISTRIBUTION_SUPERIOR_MOBILE', '')
        Taro.setStorageSync('CHEAP_PID', '')
        Taro.setStorageSync('CHEAP_ACT', '')
        Taro.setStorageSync('CHECK_REPORT_ID', '')
      })
    }
  }

  // 暂时注释
  async UNSAFE_componentWillReceiveProps(nextProps) {
    let currentCar = nextProps.car.carInfo.currentCar
    console.log('nextProps', nextProps)
    console.log('nextProps.tid', nextProps.tid)
    if (nextProps.tid.indexOf('/insurance/driving') != -1) {
      console.log('执行了吗')
      const resulte = await Taro.login()
      if (currentCar && currentCar.carLicense !== this.state.currentCar.carLicense) {
        let { query, path, rest } = this.$instance.router.params
        let selectArea = this.state.selectArea
        console.log('this.$instance.router', this.$instance.router)
        let duid: any = Taro.getStorageSync('DUID') || query && query.duid || ''
        let te: any = Taro.getStorageSync('DISTRIBUTION_LEADER_TYPE')
        let sId: any = Taro.getStorageSync('DISTRIBUTION_SHARE_ID')
        let um: any = Taro.getStorageSync('DISTRIBUTION_USER_MOBILE')
        let superiorMobile = Taro.getStorageSync('DISTRIBUTION_SUPERIOR_MOBILE')
        let pId = Taro.getStorageSync('CHEAP_PID')
        let act = Taro.getStorageSync('CHEAP_ACT')
        let rId = Taro.getStorageSync('CHECK_REPORT_ID')
        console.log('this.$router.params', this.$instance.router.params)
        if (te && te == '2') {
          path = '/insurance/upKeep/transact/puls'
          query = JSON.stringify({ type: 'oil_puls' })
        }
        if (te && te == '3') {
          path = '/insurance/upKeep/transact/puls'
          query = JSON.stringify({ type: 'tyre_puls' })
        }
        if (sId) {
          path = '/invite/share'
          query = JSON.stringify({ shareId: sId, shareMobile: um, superiorMobile: superiorMobile })
          console.log('query---query', query)
        }
        console.log('duid----duid', duid)
        if (duid) {
          path = '/retail/activity'
          query = JSON.stringify({ duid: duid })
          console.log('query--duid--query', query)
        }
        if (pId) {
          path = '/cheap/topic'
          query = JSON.stringify({ jihuasuanId: act, pId: pId })
          console.log('query---query', query)
          console.log('执行进来了吗----')
        }
        if (rId) { // 检测报告Id
          path = '/check/report'
          query = JSON.stringify({ reportId: rId })
          console.log('query---query', query)
          console.log('执行进来了吗----')
        }
        let authInfo: any = Taro.getStorageSync('IS_USERINFO')
        let distributionLeaderId: any = Taro.getStorageSync('DISTRIBUTION_LEADER_ID')
        console.log('path********', path)
        let herf = this.setHref(path, query)
        let data: paramsData = {
          duid: duid ? duid : '',
          carId: currentCar ? currentCar.id : '',
          userId: authInfo.userId,
          accessId: authInfo.accessId,
          accessKey: authInfo.accessKey,
          storeCode: Taro.getStorageSync('STORECODE'),
          serverTime: authInfo.serverTime,
          distributionLeaderId: distributionLeaderId ? distributionLeaderId : '',
          mobile: authInfo.mobile,
          thirdPartySource: Taro.getStorageSync('THIRD_PARTY_SOURCE') ? Taro.getStorageSync('THIRD_PARTY_SOURCE') : 'JEKUNAUTO',
          cityCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').adCode : '',
          areaCode: Taro.getStorageSync('CURRENT_LOCATION_INFO') ? Taro.getStorageSync('CURRENT_LOCATION_INFO').districtCode : '',
          code: resulte.code,
          selectArea

        }
        /**
         * 白名单内的域名不携带登录信息
         */
        let needLoginData = true
        whiteList.forEach(e => {
          if (path.indexOf(e) >= 0) {
            needLoginData = false
          }
        })
        let parameter = { url: herf }
        if (needLoginData) {
          parameter.data = data
        }
        let url = new CrossDomain(parameter).init()
        if (rest) {
          url = `${url}&${rest}`
        }
        this.setState({
          webUrl: '',
        }, () => {
          setTimeout(() => {
            this.setState({
              webUrl: url,
              currentCar: currentCar ? currentCar : {}
            })
            Taro.setStorageSync('DISTRIBUTION_SHARE_ID', '')
            Taro.setStorageSync('DISTRIBUTION_USER_MOBILE', '')
            Taro.setStorageSync('DISTRIBUTION_SUPERIOR_MOBILE', '')
          }, 10)
        })
      }
    }
  }


  // 获取附近门店列表
  async getNearStore(curLocation) {
    const { dispatchStore } = this.props

    let paramData = {
      userLongitude: curLocation.longitude,
      userLatitude: curLocation.latitude,
      query: {
        page: 1,
      }
    }
    let GOODS_DISTRIBUTION_ID = Taro.getStorageSync('GOODS_DISTRIBUTION_ID')
    if (GOODS_DISTRIBUTION_ID) {
      paramData.query['goodsDistributionId'] = GOODS_DISTRIBUTION_ID
      Taro.setStorageSync('GOODS_DISTRIBUTION_ID', null)
    }

    // 获取附近门店 取第一个
    await nearStore(paramData).then(async (res) => {
      const { data: { data } } = res
      if (data.length > 0) {
        await dispatchStore(data[0])
      }
    })
  }

  parseQueryString(url) {
    var params = {}
    var arr = url.split('?')
    if (arr.length <= 1)
      return params
    arr = arr[1].split('&')
    for (var i = 0, l = arr.length; i < l; i++) {
      var a = arr[i].split('=')
      params[a[0]] = a[1]
    }
    return params
  }

  // 保养年卡分享有礼处理
  onShareAppMessage() {
    console.log('分享--this.state', this.state)
    let {
      shareImgUrl,
      shareMobile,
      shareTitle,
      shareId,
      sharePath,
      superiorMobile,
      distributionUserId,
      jihuasuanId,
      cheapShshareTitle,
      cheapShareImgUrl,
      pMobile,
      ppMobile,
      cheapSharePath,
      linkType,
      referId,
      jihuasuanGoodsId,
      mobile,
      commSharePath,
      commShareTitle
    } = this.state
    if (shareId) {
      let query = {
        shareId,
        shareMobile,
        superiorMobile
      }
      console.log(`pages/webview/index/index?path=${sharePath}&query=${JSON.stringify(query)}`)
      return {
        title: shareTitle,
        path: `pages/webview/index/index?path=${sharePath}&query=${JSON.stringify(query)}`,
        imageUrl: shareImgUrl,
      }
    }
    console.log('this.$instance.router', this.$instance.router)
    if (distributionUserId) {
      let query = {
        duid: distributionUserId,
      }
      console.log(`pages/webview/index/index?path=${sharePath}&query=${JSON.stringify(query)}`)
      return {
        title: shareTitle,
        imageUrl: shareImgUrl,
        path: `pages/webview/index/index?path=${sharePath}&query=${JSON.stringify(query)}`,
      }
    }
    if (jihuasuanId) {
      // 在这里需要调取接口
      let query = {
        jihuasuanId: jihuasuanId == 999999 ? 0 : jihuasuanId,
        mobile: mobile,
        pMobile: pMobile,
        id: jihuasuanGoodsId,

      }
      if (linkType && linkType == 1) { // 商品
        query.id = referId
      }
      if (linkType && linkType == 2) { // 年卡
        query.annualCardId = referId
        query.type = 0
      }
      console.log(`pages/webview/index/index?path=${sharePath}&query=${JSON.stringify(query)}`)
      console.log('执行进来了吗')
      console.log('cheapSharePath', cheapSharePath)
      console.log('mobile', mobile)
      updateShareLog({
        jihuasuanId: jihuasuanId == 999999 ? 0 : jihuasuanId,
        mobile: mobile,
        pMobile: pMobile,
        jihuasuanGoodsId: linkType == 3 ? '' : jihuasuanGoodsId,
        source: 0,
      })
      return {
        title: cheapShshareTitle,
        imageUrl: cheapShareImgUrl,
        path: `${cheapSharePath}`,
      }
    }
    if (commSharePath) {
      return {
        title: commShareTitle,
        path: `${commSharePath}`,
      }
    }
  }

  getMessage(e) {
    console.log('eeeeee---------------eeeeeeeeeeeeeee', e)
    console.log('分享带过来的', e)
    const { dispatchStore } = this.props
    console.log('执行', e)
    //区分微信小程序还是支付宝小程序
    if (process.env.TARO_ENV === 'weapp') { // 微信小程序
      if (e && e.target && e.target.data.length) {
        let len = e.target.data.length
        let result = {}
        for (var i = 0; i < len; i++) {
          Object.assign(result, e.target.data[i])
        }
        let {
          customize,
          distributionUserId,
          path,
          query,
          storeCode,
          returnLocation,
          shareId,
          shareImgUrl,
          shareMobile,
          shareTitle,
          sharePath,
          backPath,
          superiorMobile,
          jihuasuanId,
          cheapShshareTitle,
          cheapShareImgUrl,
          pMobile,
          ppMobile,
          cheapSharePath,
          linkType,
          referId,
          jihuasuanGoodsId,
          mobile,
          commSharePath,
          commShareTitle
        } = result

        if (commSharePath) {
          this.setState({
            commSharePath,
            commShareTitle
          })
        }
        // console.log('e', e)
        if (shareId) {
          this.setState({
            shareImgUrl,
            shareMobile,
            shareTitle,
            shareId,
            sharePath,
            superiorMobile
          })
        }
        // b端分销
        if (distributionUserId) {
          this.setState({
            distributionUserId,
            sharePath,
            shareTitle,
            shareImgUrl
          })
        }
        if (jihuasuanId) { // 集划算专用
          this.setState({
            jihuasuanId,
            cheapShshareTitle,
            cheapShareImgUrl,
            pMobile,
            ppMobile,
            cheapSharePath,
            linkType,
            referId,
            jihuasuanGoodsId,
            mobile
          })
        }
        // e保养年卡分销处理
        if (backPath) {
          Taro.navigateTo({ url: `/pages/webview/index/index?path=${backPath}&query=${query}` })
        }

        // 集划算专用
        if (customize) {
          let { selectArea } = this.state
          let data = {
            selectArea
          }
          Taro.navigateTo({ url: `/pages/webview/index/index?path=${customize}&query=${JSON.stringify(data)}` })
        }

        if (path) {
          let newQuery = this.parseQueryString(path)
          if (path.includes('?')) {
            onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type : ''}` })
          } else {
            onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type : ''}` })
          }
        }
        if (storeCode) {
          // 返回storeCode 如果不一致，则更新
          const STORECODE = Taro.getStorageSync('STORECODE')
          if (Number(STORECODE) != Number(storeCode)) {
            storeInfo(
              { storeCode }
            ).then(res => {
              dispatchStore(res.data.data)
            })
          }
        }
        // 如果有返回选择门店
        if (returnLocation) {
          Taro.setStorageSync('REDIRECT_PATH', returnLocation)
        }
      }
    } else if (process.env.TARO_ENV === 'alipay') { // 支付宝小程序
      let { data } = e.detail
      let { path, query, storeCode, returnLocation, shareId, shareImgUrl, shareMobile, shareTitle, sharePath, backPath, superiorMobile } = data
      // console.log('e', e)
      if (shareId) {
        this.setState({
          shareImgUrl,
          shareMobile,
          shareTitle,
          shareId,
          sharePath,
          superiorMobile
        })
      }
      // e保养年卡分销处理
      if (backPath) {
        Taro.navigateTo({ url: `/pages/webview/index/index?path=${backPath}&query=${query}` })
      }
      if (path) {
        let newQuery = this.parseQueryString(path)
        if (path.includes('?')) {
          onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type : ''}` })
        } else {
          onNavigation({ contentType: 4, serviceItems: `${path}?type=${newQuery.type ? newQuery.type : ''}` })
        }
      }
      if (storeCode) {
        // 返回storeCode 如果不一致，则更新
        const STORECODE = Taro.getStorageSync('STORECODE')
        if (Number(STORECODE) != Number(storeCode)) {
          storeInfo(
            { storeCode }
          ).then(res => {
            dispatchStore(res.data.data)
          })
        }
      }
      // 如果有返回选择门店
      if (returnLocation) {
        Taro.setStorageSync('REDIRECT_PATH', returnLocation)
      }

    }

  }

  setHref(path, query: any) {
    path = path ? path : ''
    if (path && path.indexOf('http') !== 0) {
      path = `${domain}${path}`
    }
    console.log('query: ', query);
    return this.setUrlQuery({
      // url: `${domain}${path}`,
      url: path,
      query: query ? JSON.parse(query) : null
    })
  }

  setUrlQuery(options) {
    console.log('进来setUrlQuery', options)
    console.log('options', options)
    let { url, query } = options;
    if (!url) return '';
    if (query) {
      let queryArr: any = []
      for (const key in query) {
        if (query.hasOwnProperty(key)) {
          queryArr.push(`${key}=${query[key]}`)
        }
      }
      if (url.indexOf('?') !== -1) {
        url = `${url}&${queryArr.join('&')}`
      } else {
        url = `${url}?${queryArr.join('&')}`
      }
    }
    return url;
  }

  render() {
    const { webUrl } = this.state
    if (!webUrl) return null
    console.log(webUrl)
    return (
      <View>
        {webUrl ? <WebView src={`${webUrl}`} onMessage={(e) => this.getMessage(e)} /> : null}
      </View>
    )
  }
}
